package cn.lg.zookeeper;
// Demo3.java鐨勬簮鐮�
class MyThread extends Thread {

    private volatile boolean flag= true;
    public void stopTask() {
        flag = false;
    }
    
    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        synchronized(this) {
            try {
                int i=0;
                while (flag) {
                    Thread.sleep(1000); // 浼戠湢100ms
                    i++;
                    System.out.println(Thread.currentThread().getName()+" ("+this.getState()+") loop " + i);  
                }
            } catch (InterruptedException ie) {  
                System.out.println(Thread.currentThread().getName() +" ("+this.getState()+") catch InterruptedException.");  
            }
        }  
    }
}

public class Demo3 {

    public static void main(String[] args) {  
        try {  
            MyThread t1 = new MyThread("t1");  // 鏂板缓鈥滅嚎绋媡1鈥�
            System.out.println(t1.getName() +" ("+t1.getState()+") is new.");  

            t1.start();                      // 鍚姩鈥滅嚎绋媡1鈥�
            System.out.println(t1.getName() +" ("+t1.getState()+") is started.");  

            // 涓荤嚎绋嬩紤鐪�300ms锛岀劧鍚庝富绾跨▼缁檛1鍙戔�滀腑鏂�濇寚浠ゃ��
            Thread.sleep(300);
            t1.stopTask();
            System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");

            // 涓荤嚎绋嬩紤鐪�300ms锛岀劧鍚庢煡鐪媡1鐨勭姸鎬併��
            Thread.sleep(300);
            System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
        } catch (InterruptedException e) {  
            e.printStackTrace();
        }
    } 
}